package com.llt.config;

import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 不用的
 */
//@Configuration
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;

        // Access-Control-Allow-Origin就是我们需要设置的域名
        // Access-Control-Allow-Headers跨域允许包含的头。
        // Access-Control-Allow-Methods是允许的请求方式
        resp.setHeader("Access-Control-Allow-Origin", "*");// *,任何域名
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE,OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With, Content-Type, Accept");

        // 允许请求头Token
        // httpResponse.setHeader("Access-Control-Allow-Headers","Origin,X-Requested-With,
        // Content-Type, Accept, Token");
        // System.out.println("Token=" + req.getHeader("Token"));

        if ("OPTIONS".equals(req.getMethod())) {// axios的ajax会发两次请求，第一次提交方式为：option，直接返回即可
            return;
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
